package com.example.springbootexam.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.example.springbootexam.bean.Paper;
import com.example.springbootexam.bean.Result;
import com.example.springbootexam.bean.User;
import com.example.springbootexam.biz.BizExeption;
import com.example.springbootexam.biz.PaperBiz;
import com.example.springbootexam.mapper.PaperMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ly
 * @since 2024-08-14
 */
@RestController
@RequestMapping("/paper")
public class PaperController {

    @Autowired
    PaperBiz paperBiz;

    @RequestMapping("add")
    public Result add(@RequestBody @Valid Paper paper, Errors errors,
                      @SessionAttribute User myinfo){
        //表单验证
        if(paper.getBegin() == null || paper.getEnd() == null ){
            if (errors.hasErrors()){
                return new Result(0,"考卷信息错误",errors.getAllErrors());
            }
        }else {
            if (paper.getBegin().after(paper.getEnd())) {
                errors.rejectValue("begin","begin_error","开考时间必须在结考时间之前");
            }
        }
        if (paper.getScoreTotal() == 0) {
            errors.rejectValue("scoreTotal","scoreTotal_error","总分不能为零;请选择题目");
        }
        if (paper.getTime() == 0) {
            errors.rejectValue("time","time_error","考试时间不能为零");
        }
        if (errors.hasErrors()){
            return new Result(0,"考卷信息错误",errors.getAllErrors());
        }

        System.out.println("paper = " + paper);

        try {
            paper.setCreateUid(myinfo.getId());
            paperBiz.create(paper);
        } catch (BizExeption e) {
            return new Result(0,e.getMessage(),null);
        }

        return new Result(1,"考卷提交成功!",null);
    }

    @Autowired
    PaperMapper paperMapper;
    @RequestMapping("query")
    public Page<Paper> query(@RequestBody Paper paper,
                             @RequestParam(defaultValue = "1") int current,
                             @RequestParam(defaultValue = "5") int size){
        LambdaQueryWrapper<Paper> lqw = new LambdaQueryWrapper<>();
        if(paper.getTitle()!=null&&paper.getTitle().isBlank()==false){
            lqw.like(Paper::getTitle, paper.getTitle());
        }
        Page<Paper> p = new PageDTO<>(current, size);
        return paperMapper.selectPage(p, lqw);
    }

    @RequestMapping("get")
    public Paper findById(int id){
        return paperMapper.findById(id);
    }

}

